/* eslint-disable prettier/prettier */
import { useMemberStore } from "@/stores";

const baseURL='https://pcapi-xiaotuxian-front-devtest.itheima.net';

const httpInterceptor={
  invoke(options:UniApp.RequestOptions){
    if(!options.url.startsWith('http')){
      options.url=baseURL+options.url;
    }
    options.timeout=10000;
    options.header={
       ...options.header,
      'source-client':'miniapp',
    };
    //添加token
    const memberStore = useMemberStore()
    const token = memberStore.profile?.token
    if(token){
      options.header.Authorization = token;
    }
  }
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor);

export interface Data<T>{
  code:string;
  msg: string;
  result: T
}

/**
 * request封装请求
 * @param options 参数json
 * @returns
 */
export const http=<T>(options:UniApp.RequestOptions)=>{
  return new Promise<Data<T>>((resolve,reject)=>{
    uni.request({
      ...options,
      success:(res)=>{
        if (res.statusCode >= 200 && res.statusCode < 300) {
           resolve(res.data as Data<T>)
         }else if(res.statusCode==401){
           const memberStore = useMemberStore()
           memberStore.clearProfile();
           uni.navigateTo({url:'/pages/login/login'});
           reject(res);
         }else{
          uni.showToast({icon:'none',title:(res.data as Data<T> )?.msg || '请求错误'})
         }
      },fail(err){
         //网络错误
         uni.showToast({
           icon:'error',
           title:'网络错误'
         })
      }
    })
  })
}

export function httpGet<T>(options:UniApp.RequestOptions){
  options.method='GET';
  return http<T>(options);
}

export function httpPost<T>(options:UniApp.RequestOptions){
  options.method='POST';
  return http<T>(options);
}
export function httpDelete<T>(options:UniApp.RequestOptions){
  options.method='DELETE';
  return http<T>(options);
}
export function httpPut<T>(options:UniApp.RequestOptions){
  options.method='PUT';
  return http<T>(options);
}
